<!--
 * @Author: 常安民 changanmin1@crdigital.com.cn
 * @Date: 2024-07-26 18:10:50
 * @LastEditors: 常安民 changanmin1@crdigital.com.cn
 * @LastEditTime: 2024-08-05 16:16:10
 * @FilePath: /console-web/src/views/trip/manager/standard/standard.vue
 * @Description: 差标管理
 * @email:anmin@foxmail.com
 * Copyright (c) 2024 by 华润数科控股有限公司/常安民, All Rights Reserved. 
-->
<template>
  <!-- 页面-角色管理 -->
  <div class="innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <FormItem prop="travelStandardCode" label="差标编码">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardCode']"
              placeholder="请输入差标编码"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="travelStandardName" label="差标名称">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm['travelStandardName']"
              placeholder="请输入差标名称"
              clearable
              @on-enter="search"
            ></Input>
          </FormItem>
          <FormItem prop="tenantCode" label="所属租户" v-if="isPlatformAdmin">
            <Select
              label-in-value
              filterable
              v-model="searchForm.tenantCode"
              style="width: 100%" 
              clearable
            >
              <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                {{ tenant.tenantName }}  -  {{ tenant.tenantCode }}
              </Option>
            </Select>
          </FormItem> 
          <!-- 状态 -->
          <FormItem prop="enabled" :label="$t('common.status')">
            <Select
              style="width: 100%;"
              v-model.trim="searchForm.enabled"
              :placeholder="$t('common.warning.selectStatus')"
              clearable
            >
              <Option v-for="(item, index) in searchStatusList" :value="item.vsiKey" :key="index">{{
                item.vsiValue
              }}</Option>
            </Select>
          </FormItem>
          <!-- 查询\重置按钮 -->
          <FormItem prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </FormItem>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="searchTable" :config="tableConfig" v-if="this.userRolePermission || this.appRolePermission">
      <!-- handler bar 查询/重置-->
      <!--
        <div slot="handle-bar">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="reset" />
        </div>
        -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="onOpenAddPage" v-permission="'ROLE_INDEX'" /> 
        <RPButton shape="circle" text="test" @click="onTest" v-show="false" />
        <!--  -->
        <Dropdown @on-click="onDownMenu">
          <Button type="primary">
             批量操作
              <Icon type="ios-arrow-down"></Icon>
          </Button>
          <DropdownMenu slot="list">
              <DropdownItem name="enabled">启用</DropdownItem>
              <DropdownItem name="del">删除</DropdownItem> 
              <DropdownItem name="disabled">禁用</DropdownItem> 
          </DropdownMenu>
      </Dropdown>
        <!-- <RPButton optType="delete" @click="deleted" /> -->
        <!-- <RPButton optType="enable" @click="toggleLock(1)" />
          <RPButton optType="disable" @click="toggleLock(0)" />-->
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import { apiQueryStandardPage, apiStandardBatchOperate, apiStandardTest } from '@api/trip/standard/standard.js';
import debounce from "lodash/debounce";

import tenantAPI from "@/api/tenantApi.js";
// import RoleUserListMg from "./RoleUserListManage.vue";
import { searchAppListByTenantCode } from '@/api/applicationApi.js';

import valueSetAPI from '@/api/valueSetAPI.js';
import { CoreModuleName } from '@/const.js';
// import AuthorizedUser from './AuthorizedUser.vue'
// import PermissionEditForAppRole from './PermissionEditForAppRole.vue'
// import RoleAssignApp from './RoleAssignApp.vue'
// import RoleAssignDimension from './RoleAssignDimension.vue'
// import RoleAssignMenu from './RoleAssignMenu.vue'
// import RoleDetail from './RoleDetail.vue'
// import RoleEdit from './RoleEdit.vue'
import { mapGetters } from 'vuex';
export default {
  name: 'trip-manager-standard',
  mixins: [],
  data() {
    return {
      title: '差标管理',
      category: 1, // 当前登录用户的用户类型
      isQueryMenusAndBtns: false,
      rolePermissonModalTitle: this.$t('module.role.permissionMaList'),
      searchStatusList: [], //状态下拉框数据
      tenantList:[],
      searchForm: {
       
        // id:"",//
        // tenantCode: $store.state[CoreModuleName].userInfo.tenantCode,//租户编码
        travelStandardCode:"",//差标编码
        travelStandardName:"",//
        // customerCode:"",//客户编码
        // customerName:"",//
        // ouCodes:"",//
        // ouNames:"",//
        // travelPositionCode:"",//职级编码
        // travelPositionName:"",//
        // isApplyBill:"",//是否需要申请单
        // isBudget:"",//是否预算管控
        enabled:'',//是否有效，1有效，0无效
        // createUser:"",//
        // updateUser:"",//
        // updateTime:"",//
      },
      roleTypeList: {},
      appList: {},
      searchTypeList: [
        {
          key: 'roleName',
          name: this.$t('module.role.roleName'),
          placeholder: this.$t('module.role.warning.enterRoleName')
        },
        {
          key: 'roleCode',
          name: this.$t('module.role.roleCode'),
          placeholder: this.$t('module.role.warning.enterRoleCode')
        },
        {
          key: 'menuCode',
          name: this.$t('module.role.menuCode'),
          placeholder: this.$t('module.role.warning.enterMenuCode')
        }
      ],
      searchTypePlaceholder: this.$t('module.role.warning.enterRoleName')
    }
  }, 
  watch: {
    // 'searchForm.searchType': {
    //   handler() {
    //     let selectItem = this.searchTypeList.find(item => item.key == this.searchForm.searchType)
    //     this.searchTypePlaceholder = selectItem ? selectItem.placeholder : ''
    //   }
    // }
  },
  computed: {
    ...mapGetters(['isPlatformAdmin']),
    tableConfig() {
      return {
        border:true,
        loadDataFn: this.queryListByPage,
        columnsFn: () => {
          let columns =  [
            {
              type: 'selection',
              width: 50,
              align: 'center'
            },
            {
              title: '差标编码',
              key: 'travelStandardCode',
              width: 180,
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title =  params.row['travelStandardCode'] 
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '差标名称',
              key: 'travelStandardName',
              width: 280,
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: params.row['travelStandardName']
                    }
                  },
                  params.row['travelStandardName']
                )
              }
            },
            {
              title: '所属租户',
              key: 'tenantCode',
              align: 'center',
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title = this.tenantByName[params.row['tenantCode']] + `(${params.row['tenantCode']})`
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title 
                    }
                  },
                  title
                )
              }
            },
            // {
            //   title: '所属租户',
            //   key: 'customerName',
            //   align: 'center',
            //   resizable:true,
            //   sortable: 'custom',
            //   render: (h, params) => {
            //     let title =  params.row.customerName
            //     return h(
            //       'div',
            //       {
            //         attrs: {
            //           class: 'ivu-table-cell ivu-table-cell-ellipsis',
            //           title: title 
            //         }
            //       },
            //       title
            //     )
            //   }
            // }, 
            {
              title: '归属公司',
              key: 'ouNames',
              align: 'center',
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['ouNames'] 
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title 
                    }
                  },
                  title
                )
              }
            }, 
            {
              title: this.$t('common.describe'), // 备注 改为 描述
              key: 'remark',
              minWidth: 120,
              render: (h, params) => {
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: params.row.remark
                    }
                  },
                  params.row.remark
                )
              }
            },
            {
              title: this.$t('common.status'),
              align: 'center',
              key: 'enabled', 
              width:100,
              render: (h, params) => {
                return h(
                  'StatusButton',
                  {
                    // 修改StatusButton内容居中
                    style: {
                      'justify-content': 'center'
                    },
                    props: {
                      status: params.row.enabled == '1' ? '0' : '1'
                    }
                  },
                  params.row.enabled == '1' ? this.$t('common.enable') : this.$t('common.disable')
                )
              }
            },
            {
              title: '更新时间',
              key: 'updateTime',
              align: 'center',
              resizable:true,
              width:160,
              render: (h, {row:{updateUser,updateTime}}) => {
                let txt =  updateUser &&updateTime ?`${updateTime}(${updateUser})`:''
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: txt
                    }
                  },
                  txt
                )
              }
            },{
              title: '创建时间',
              key: 'createTime',
              align: 'center',
              resizable:true,
              width:220,
              render: (h, {row:{createUser,createTime}}) => {
                let txt =  createUser &&createTime ?`${createTime}(${createUser})`:''
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: txt
                    }
                  },
                  txt
                )
              }
            },
            {
              title: this.$t('common.operating'),
              align: 'left',
              fixed: 'right',
              resizable:true,
              width: 150,
              render: (h, { row }) => {
                let data = []
                if (row.enabled == '1') {
                  data = [
                    {
                      text: '编辑',
                      handle:  debounce(()=>this.onOpenEditPage(row),300)
                    },
                    {
                      text: '禁用',
                      handle:debounce(()=>this.onUpdate(row,0),300)
                    },
                    // {
                    //   text: '删除',
                    //   handle: debounce(()=>this.onDel(row),300)
                    // }
                  ]
                } else {
                  data = [
                    {
                      text: '编辑',
                      handle:  debounce(()=>this.onOpenEditPage(row),300)
                    },
                    {
                      text: '启用',
                      handle:debounce(()=>this.onUpdate(row,1),300)
                    },
                    {
                      text: '删除',
                      handle: debounce(()=>this.onDel(row),300)
                    }
                  ]
                }
                return h('RowTools', {
                  props: {
                    data: data
                  }
                })
              }
            }
          ];
          if(!this.isPlatformAdmin){
            columns = columns.filter(item=>{
              if(item.key == 'tenantCode'){
                return false;
              }
              return true;
            })
          } 
          return columns;
        },
        autoFirst: false,
        rowClassNameFn: this.rowClassName // 自定义行样式
      }
    },
    userRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_USER')
      }
    },
    appRolePermission() {
      if ($store.state['ripples-components'].resList) {
        return $util.checkPermission('ROLE_TYPE_APP')
      }
    },
    tenantByName(){
      let tenantCodes = {};
      this.tenantList.map(item=>{
        tenantCodes[item.tenantCode] = item.tenantName;
      });
      return tenantCodes;
    }
  },
  created: function() {
    this.getStateSelect()
    this.tenantList = []
  },
  mounted() {
    if(this.isPlatformAdmin){
      // 平台管理员可以搜索租户信息
      this.$set(this.searchForm,'tenantCode','')
       /**
         * 加载所有租户
         */
         tenantAPI.queryTenantList().then(data => {
          // const {tenantName ,tenantCode,id }
          this.tenantList = data;
        })
    }
    this.init()
  },
  methods: {
    onTest(){
      apiStandardTest().then(res=>{
        console.log('res :>> ', res);
      })
    },
    /**
     * 获取表格中选择的行ID
     */
    getSelectedIds() {
      let list = this.$refs['searchTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    },
    onDownMenu(name){
      let ids = this.getSelectedIds();
      if(ids.length > 0){  
        switch (name) {
          case 'enabled': 
            new $confirm("您确定要启用所选择的差标数据吗？", this).then(() => {
              // enabled 1 启用
              apiStandardBatchOperate({ids:ids.join(','),enabled:'1'})
                .then(res => {
                  this.$message.success({
                    content: "启用成功",
                    duration: 3
                  })
                  this.search()
                })
                .catch(data => {
                  this.$message.error({
                    content: data.message,
                    duration: 3
                  })
                })
            })
            break;
          case 'del':
            // 删除
            new $confirm("您确定要删除所选择的差标数据吗？", this).then(() => {  
              // enabled 2 删除
              apiStandardBatchOperate({ids:ids.join(','),enabled:'2'})
                .then(res => {
                  this.$message.success({
                    content: "删除成功",
                    duration: 3
                  })
                  this.search()
                })
                .catch(data => {
                  this.$message.error({
                    content: data.message,
                    duration: 3
                  })
                })
            })
            break;
          case 'disabled': 
            new $confirm("您确定要禁用所选择的差标数据吗？", this).then(() => {
              // enabled 0 禁用
              apiStandardBatchOperate({ids:ids.join(','),enabled:'0'})
                .then(res => {
                  this.$message.success({
                    content: "禁用成功",
                    duration: 3
                  })
                  this.search()
                })
                .catch(data => {
                  this.$message.error({
                    content: data.message,
                    duration: 3
                  })
                })
            })
            break;
        }
      }
    },  
    // 自定义行样式
    rowClassName(row) {
      //关联的菜单中是否存在有效的hasEnabledMenu:1-存在,0-不存在。enabled:1-有效，0-无效。roleType：1-用户角色，2-应用角色
      if (row.hasEnabledMenu == 0 && row.enabled == 1 && row.roleType == 1) {
        return 'tableDisableStyle'
      }
    },
    // 获取状态下拉数据
    async getStateSelect() {
      const [searchStatusList = []] = await Promise.all([valueSetAPI.getValueSetByCode('ENABLED_CODE')])
      searchStatusList.map((item, index) => {
        if (item.vsiKey == 'ALL') {
          searchStatusList.splice(index, 1)
        }
      })
      this.searchStatusList = searchStatusList
    },
    async init() {
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return
      this.category = userInfo.category
      // 根据当前租户查询数据
      // this.searchForm.tenantCode = userInfo.tenantCode
      const [ appData] = await Promise.all([
        // valueSetAPI.getValueSetByCode('ROLE_TYPE'),
        searchAppListByTenantCode({
          pageNum: 1,
          pageSize: 200,
          condition: {
            tenantCode: userInfo.tenantCode
          }
        })
      ])
      console.log('appData :>> ', appData) 
      // 查询列表
      this.search()
    },

    
    search(page = 1) {
      let searchParams = Object.assign({}, this.searchForm) 
      this.$refs['searchTable'].load(searchParams, page) 
    },
    reset() {
      this.$refs['searchForm'].resetFields() 
      this.search(1)
    }, 
    onUpdate(row,enabled){ 
      let title = enabled == 1?'启用':'禁用'
      new $confirm("您确定要"+title+"该行差标数据吗？", this).then(() => { 
              // enabled 0 禁用
      apiStandardBatchOperate({ids:row.id+'',enabled:enabled+''})
          .then(res => {
            this.$message.success({
              content: "修改成功",
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    onDel(row){
      new $confirm("您确定要删除该行差标数据吗？", this).then(() => { 
        apiStandardBatchOperate({ids:row.id+'',enabled:'2'})
          .then(res => {
            this.$message.success({
              content: this.$t('module.orgManage.deleteSuccess'),
              duration: 3
            })
            this.search()
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            })
          })
      })
    },
    onOpenEditPage(row){
      new this.$sidelipPage(
        () => import('./standardDetail.vue'),
        {
          props: {
            id: row.id, 
          },
          isActionTop: false,  
        },
        data => {
          data && this.search()
        }
      )
    },
    onOpenAddPage:debounce(function(){ 
      new this.$sidelipPage(
        () => import('./standardDetail.vue'),
        {
          props: {
            disabled:false,
          },
          isActionTop: false,  
        },
        data => {
          data && this.search()
        }
      )
    //   new this.$pageModal(
    //     () => import('./standardDetail.vue'),
    //     {
    //       props: {
    //         tenantCode: this.searchForm.tenantCode
    //       }
    //     },
    //     data => {
    //       data && this.search()
    //     }
    //   ) 
    },300),
  
    getDateString(DateStr) {
      if (DateStr == undefined || DateStr == null || DateStr == '' || DateStr.trim() == '') {
        return ''
      }
      // return DateStr.split(" ")[0];
      let dateList = DateStr.split(' ')[0].split('-')
      let newDateList = []
      let newItem = ''
      for (let key = 0; key < dateList.length; key++) {
        let newNummber = parseInt(dateList[key])
        if (newNummber < 10) {
          newNummber = '0' + newNummber
        }
        newDateList.push(newNummber)
      }
      return newDateList.join('-')
    }, 
    queryListByPage({ responseProcess, param }) {
      console.log('param :>> ', param);
      return apiQueryStandardPage(param).then(data => {
        console.log('data :>> ', data);
        if(data.success){ 
          responseProcess(data.data)
        }else{
          this.$message.error({
              content: data.message || "未查询到差标信息",
              duration: 3
          });
          responseProcess({records:[]})
        }
      })
    }
  }
}
</script>

<style></style>
